import socket
import time


class rtuandtcpip:
    def __init__(self) -> None:
        self.host = '192.168.12.225'
        self.port = 8000
        self.buffer = 1024
        self.addr = (self.host, self.port)
        self.tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcpSock.connect(self.addr)

    def set_temp(self, data):
        if -50 <= data < 156:
            a = int(data * 10)
            a1 = int((a >> 8) & 0xff)
            a2 = int(a & 0xff)
            b = bytes([a1, a2])
            print(b)
            self.tcpSock.send(b'\x00\x01\x00\x00\x00\x06\x01\x06\x07\xCF' + b)
        else:
            print('您输入的温度超范围；请注意！！！')

    def set_humi(self, data):
        if 0 <= data < 100:
            a = int(data * 10)
            a1 = int((a >> 8) & 0xff)
            a2 = int(a & 0xff)
            b = bytes([a1, a2])
        # print(b)
            self.tcpSock.send(b'\x00\x01\x00\x00\x00\x06\x01\x06\x07\xD0' + b)
        else:
            print('您输入的湿度超范围；请注意！！！')

    def read_temp(self):
        self.tcpSock.send(b'\x00\x01\x00\x00\x00\x06\x01\x04\x08\x33\x00\x01')
        ret = self.tcpSock.recv(2000)
        # print(ret)
        ret = list(ret[-2:])
        # print(ret)
        temp = -(65536 - (ret[0] * 256 + ret[1])) / 10 if ret[0] > 128 else (ret[0] * 256 + ret[1]) / 10
        # print(temp)
        return temp
    
    def read_humi(self):
        self.tcpSock.send(b'\x00\x01\x00\x00\x00\x06\x01\x04\x08\x35\x00\x01')
        ret = self.tcpSock.recv(2000)
        # print(ret)
        ret = list(ret[-2:])
        # print(ret)
        humi = (ret[0] * 256 + ret[1]) / 10
        # print(temp)
        return humi
    def set_temp_speed(self, data):
        print('设置温度速率！')
    def set_humi_speed(self, data):
        print('设置湿度速率！')
    
    def set_humi_enable(self):
        self.tcpSock.send(b'\x00\x01\x00\x00\x00\x06\x01\x05\x7d\x91\x00\x01')  
        print('')
    def set_humi_disable(self):
        self.tcpSock.send(b'\x00\x01\x00\x00\x00\x06\x01\x05\x7d\x91\x00\x00') 
        print('')
    
    def run(self):
        self.tcpSock.send(b'\x00\x01\x00\x00\x00\x06\x01\x05\x81\x1f\xff\x00')  

    def stop(self):
        self.tcpSock.send(b'\x00\x01\x00\x00\x00\x06\x01\x05\x81\x21\xff\x00')

if __name__ == "__main__":
    dht = rtuandtcpip()
    temp = 35
    dht.set_temp(temp)
    dht.run()
    temp_read = dht.read_temp()

    while abs(temp - temp_read) > 0.5:
        time.sleep(5)
        temp_read = dht.read_temp()
        print(temp_read)
    dht.stop()
    # a.set_humi_enable()
    # a.set_humi_disable()  
    # a.run()
    # a.stop()
    # a.set_temp(b'\x03\x52') #85
